#include "head.h"

/*
Usage:
*/

enum command get_cmd(int client_fd, char* arg){
    struct train msg;
    bzero(&msg,sizeof(msg));
    int ret=recv(client_fd,&msg,sizeof(msg),MSG_WAITALL);
    if(ret==0)
    {
        //printf("client is disconnected\n");
        close(client_fd);
        return client_exit;
    }
    enum command cmd_num = msg.op;

    bzero(arg,sizeof(char)*200);
    strncpy(arg,msg.path,sizeof(char)*200);

    return cmd_num;
}

int cmd_analyse(int client_fd, enum command op, char *arg, char *cur_path){
   
    switch(op)
    {

    case ls:
        server_ls(client_fd,cur_path);
        break;
    case cd:
        server_cd(client_fd,arg,cur_path);
        break;
    case pwd:
        break;
    case download:
        server_download(client_fd, arg, cur_path);
        break;
    case upload:
        server_upload(client_fd, arg, cur_path);
        break;
    case rm:
        server_rm(client_fd,arg,cur_path);
        break;
    case cdir:
        server_cdir(client_fd,arg,cur_path);
        break;
    default :
        printf("error:invaild command\n");

    }
    return 0;
}

int work_program(int client_fd){
    char cur_path[200]={0};
    char arg[200]={0};

    // 调用getcwd函数，获取当前工作目录
    if (getcwd(cur_path, sizeof(cur_path)) != NULL) {

    } else {
        perror("getcwd() error");
    }




    printf("enter pthread\n");
    int ret_login = server_login(client_fd,cur_path);
    if(ret_login != 0){
        return 0;
    }

    //走到这里，登录成功，设置epoll监听客户端消息；
    int epoll_fd = epoll_create(1);
    addtoEpoll(epoll_fd,client_fd);

    while(true){
        struct epoll_event ready_set[10];
        int ready_num = epoll_wait(epoll_fd,ready_set,10,-1);
        for(int i=0; i<ready_num; i++){
            if(ready_set[i].data.fd == client_fd){
                enum command cmd = get_cmd(client_fd,arg);//分析命令
                if(cmd==client_exit)
                {
                    close(client_fd);
                    return -1;
                }
                cmd_analyse(client_fd,cmd,arg,cur_path);  //选择命令并且执行
            }
        }
    }

    return 0;
}

void* threadMain(void *p){
    while(1){

        thread_poll *poll = (thread_poll*)p;
        pthread_mutex_lock(&poll->lock);
        while(poll->sessions.queue_size == 0){
            pthread_cond_wait(&poll->cond,&poll->lock);
        }
        int client_fd = dequeue(&poll->sessions);
        if(client_fd == -1){
            printf("error: empty queue!\n");
            break;
        }
        pthread_mutex_unlock(&poll->lock);
        work_program(client_fd);
        close(client_fd);
    }

}
